import 'package:flutter/material.dart';

class HabitLibraryScreen extends StatefulWidget {
  const HabitLibraryScreen({Key? key}) : super(key: key);

  @override
  _HabitLibraryScreenState createState() => _HabitLibraryScreenState();
}

class _HabitLibraryScreenState extends State<HabitLibraryScreen> {
  int _selectedCategoryIndex = 0;
  
  final List<String> _categories = [
    '推荐', '健康', '学习', '工作', '生活', '关系', '冥想', '理财'
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('习惯库'),
        elevation: 0,
      ),
      body: Column(
        children: [
          _buildSearchBar(),
          _buildCategoryTabs(),
          Expanded(
            child: _buildLibraryContent(),
          ),
        ],
      ),
    );
  }
  
  Widget _buildSearchBar() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 5,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: TextField(
        decoration: InputDecoration(
          hintText: '搜索习惯',
          prefixIcon: const Icon(Icons.search, color: Colors.grey),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
            borderSide: BorderSide.none,
          ),
          filled: true,
          fillColor: Colors.grey.shade100,
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 15,
            vertical: 10,
          ),
        ),
      ),
    );
  }
  
  Widget _buildCategoryTabs() {
    return Container(
      height: 50,
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 3,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: _categories.length,
        itemBuilder: (context, index) {
          return _buildCategoryTab(index);
        },
      ),
    );
  }
  
  Widget _buildCategoryTab(int index) {
    final isSelected = _selectedCategoryIndex == index;
    
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedCategoryIndex = index;
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              width: 3,
              color: isSelected
                  ? Theme.of(context).primaryColor
                  : Colors.transparent,
            ),
          ),
        ),
        child: Text(
          _categories[index],
          style: TextStyle(
            color: isSelected
                ? Theme.of(context).primaryColor
                : Colors.grey,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ),
    );
  }
  
  Widget _buildLibraryContent() {
    return ListView(
      padding: const EdgeInsets.all(15),
      children: [
        _buildTheoryCard(),
        const SizedBox(height: 20),
        const Text(
          '推荐习惯',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 15),
        _buildHabitGrid(),
        const SizedBox(height: 20),
        _buildHabitDetail(),
      ],
    );
  }
  
  Widget _buildTheoryCard() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: const Color(0xFFF1F8E9),
        borderRadius: BorderRadius.circular(10),
        border: const Border(
          left: BorderSide(
            color: Color(0xFF4CAF50),
            width: 4,
          ),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '习惯四法则',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF2E7D32),
            ),
          ),
          const SizedBox(height: 10),
          const Text(
            '詹姆斯·克利尔在《掌控习惯》中提出了习惯形成的四个步骤：明显的提示、强烈的渴望、简单的行动和即时的奖励。这四个步骤构成了习惯形成的基础。',
            style: TextStyle(
              fontSize: 14,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {
              // 查看详情
            },
            child: const Text('查看详情'),
            style: ElevatedButton.styleFrom(
              primary: const Color(0xFF4CAF50),
              elevation: 0,
              minimumSize: const Size(double.infinity, 40),
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildHabitGrid() {
    return GridView.count(
      crossAxisCount: 2,
      crossAxisSpacing: 15,
      mainAxisSpacing: 15,
      childAspectRatio: 0.8,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      children: [
        _buildHabitCard(
          '晨跑5公里',
          '清晨跑步能提高新陈代谢，增强体能，提升一天的精力水平。',
          Icons.directions_run,
          12354,
        ),
        _buildHabitCard(
          '每日阅读30分钟',
          '每天阅读能扩展知识，提高思维能力，是最有价值的习惯之一。',
          Icons.book,
          18732,
        ),
        _buildHabitCard(
          '喝水2000ml',
          '充足的水分摄入对身体的各项功能都至关重要，提高集中力和精力。',
          Icons.local_drink,
          24123,
        ),
        _buildHabitCard(
          '晚上10:30睡觉',
          '规律的睡眠能提高免疫力，改善记忆力，促进身体恢复。',
          Icons.nightlight_round,
          9845,
        ),
      ],
    );
  }
  
  Widget _buildHabitCard(
      String title,
      String description,
      IconData icon,
      int userCount,
  ) {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: const Color(0xFFE8F5E9),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Icon(
              icon,
              color: const Color(0xFF4CAF50),
              size: 20,
            ),
          ),
          const SizedBox(height: 10),
          Text(
            title,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 15,
            ),
          ),
          const SizedBox(height: 5),
          Expanded(
            child: Text(
              description,
              style: const TextStyle(
                fontSize: 12,
                color: Colors.grey,
              ),
            ),
          ),
          Row(
            children: [
              const Icon(
                Icons.people,
                color: Color(0xFF4CAF50),
                size: 14,
              ),
              const SizedBox(width: 5),
              Text(
                '$userCount人已添加',
                style: const TextStyle(
                  fontSize: 12,
                  color: Color(0xFF4CAF50),
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {
              // 添加习惯
            },
            child: const Text('添加习惯'),
            style: ElevatedButton.styleFrom(
              primary: const Color(0xFF4CAF50),
              elevation: 0,
              minimumSize: const Size(double.infinity, 32),
              textStyle: const TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildHabitDetail() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(
                  color: const Color(0xFFE8F5E9),
                  borderRadius: BorderRadius.circular(25),
                ),
                child: const Icon(
                  Icons.spa,
                  color: Color(0xFF4CAF50),
                  size: 25,
                ),
              ),
              const SizedBox(width: 15),
              const Expanded(
                child: Text(
                  '每日冥想',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 18,
                  ),
                ),
              ),
              const Text(
                '15,426人已添加',
                style: TextStyle(
                  color: Color(0xFF4CAF50),
                  fontSize: 14,
                ),
              ),
            ],
          ),
          const SizedBox(height: 15),
          const Text(
            '习惯描述',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Color(0xFF4CAF50),
            ),
          ),
          const SizedBox(height: 10),
          const Text(
            '冥想是科学证实的减压方法，能提高专注力，改善情绪状态，增强自我意识。每天只需10-15分钟，就能带来长期的心理和生理益处。',
            style: TextStyle(
              fontSize: 14,
            ),
          ),
          const SizedBox(height: 15),
          const Text(
            '四步习惯养成法',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Color(0xFF4CAF50),
            ),
          ),
          const SizedBox(height: 10),
          _buildHabitStep(
            1,
            '明显的提示',
            '在固定时间（如早上起床后）、固定地点（在客厅或卧室）进行冥想，或配合其他已有习惯之后（如喝完晨间咖啡后）。',
          ),
          _buildHabitStep(
            2,
            '强烈的渴望',
            '想象冥想带给你的平静感受，以及提高工作效率和减少焦虑的长期好处。',
          ),
          _buildHabitStep(
            3,
            '简单的行动',
            '开始时只冥想2分钟，逐渐增加到10-15分钟。准备舒适的坐垫和安静的环境，或使用引导冥想应用。',
          ),
          _buildHabitStep(
            4,
            '即时的奖励',
            '冥想后记录自己的平静感受，或奖励自己喜欢的健康饮品。在应用中查看连续坚持天数的成就。',
          ),
          const SizedBox(height: 15),
          ElevatedButton(
            onPressed: () {
              // 添加到我的习惯
            },
            child: const Text('添加到我的习惯'),
            style: ElevatedButton.styleFrom(
              primary: const Color(0xFF4CAF50),
              elevation: 0,
              minimumSize: const Size(double.infinity, 45),
              textStyle: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildHabitStep(int stepNumber, String title, String description) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 25,
            height: 25,
            decoration: BoxDecoration(
              color: const Color(0xFF4CAF50),
              borderRadius: BorderRadius.circular(12.5),
            ),
            alignment: Alignment.center,
            child: Text(
              stepNumber.toString(),
              style: const TextStyle(
                color: Colors.white,
                fontSize: 12,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 14,
                  ),
                ),
                const SizedBox(height: 5),
                Text(
                  description,
                  style: const TextStyle(
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
